from flask import Flask, render_template, jsonify, request
import pandas as pd
from openpyxl import load_workbook
import pathlib


app = Flask(__name__)

# 获取excel的相对路径
cur_path = pathlib.Path(__file__).absolute()
excel_path = cur_path.parent/"static/data/networks.xlsx"
print(excel_path)
colors = ["#900021", "#FBD26A", "#8F4B28", "#01847F", "#40E0D0", "#002FA7", "#81D8CF", "#003152", "#B05923", "#E60000"]
group_info = {}
new_data = {}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_options', methods=['GET'])
def get_options():
    wb = load_workbook(excel_path)
    sheetnames = wb.sheetnames
    data_sources = []
    for sheetname in sheetnames:
        data_sources.append({"label": sheetname, "value": sheetname})
    wb.close()
    return jsonify({"options": data_sources})

@app.route('/topology')
def topology():
    topology_data = new_data
    print(group_info)
    new_data["group_info"] = group_info
    return jsonify(topology_data)

@app.route('/load_data', methods=['POST'])
def load_data():
    global new_data
    global group_info
    data = request.get_json()
    sheetname = data.get('sheetname')
    print(sheetname)
    wb = load_workbook(excel_path)
    sheet = wb[sheetname]
    titles = []
    new_data={"nodes": [],"links": []}
    it=0
    for row in sheet.iter_rows(values_only=True):
        if it==0:
            group_info = {}
            item = row[2]
            if item is not None:
                ones = item.split(",")
                for one in ones:
                    ind, name = one.split(":")
                    ind = int(ind)
                    group_info[ind] = {"name": name, "color": colors[ind-1]}
            it += 1
            print(group_info)
            continue
        elif it==1:
            titles = row
        else:
            id=row[0]
            group=row[1]
            ip = row[2]
            card = row[3]
            if id is None or group is None:
                return jsonify("fail", "id or group is wrong")
            id = str(id)
            if ip is None:
                ip = ""
            if card is None:
                card = ""
            node = {"id": id, "group": int(group), "ip": ip, "card": card}
            new_data["nodes"].append(node)
            if row[4] is not None:
                conns = str(row[4]).split(',')
                for conn in conns:
                    link = {"source": id, "target": conn, "value": 1}
                    new_data["links"].append(link)
        it += 1
    print("success change")
    wb.close()

    return jsonify({'success': True})


if __name__ == '__main__':
    app.run(debug=True)
